package com.ossean.util;

import java.security.acl.LastOwnerException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringHandler {
	
	public static String getFirstSentence(String sentence){
		if(sentence == null)
			return null;
		int index = -1;
		int indexEng = sentence.indexOf(".");
		int indexChi = sentence.indexOf("。");//中文句号
		if(indexChi < 0){
			index = indexEng;
		}else if(indexEng < 0){
			index = indexChi;
		}else{
			index = indexEng < indexChi?indexEng:indexChi;
		}
		if(index > 0){
			sentence = sentence.substring(0, index+1);
		}
		return sentence;
	}
	
	public static String findLinkName(String str, String beWord){
		String result = null;
		int index = str.indexOf(beWord);
		if(index > 0 && index < 100){
			//如果超过100个字符，默认不是定义语句(暂没有找到论文根据)
			result = str.substring(0, index).trim();
		}
		return result;
	}
	public static String [] splitTagsByBracket(String tagstr){
		String [] resultStrArr;
		resultStrArr = tagstr.split("\\<|\\>");
		List<String> tmp = new ArrayList<String>();  
	    for(String str:resultStrArr){  
	        if(str!=null && str.length()!=0){  
	            tmp.add(str);  
	        }  
	    }  
	    resultStrArr = tmp.toArray(new String[0]);
	    return resultStrArr;
	}
	
	public static boolean compareLanguage(String str1,String str2){
		
		//str1是来自oschina的项目语言信息
		/*
		 *openhub: C++|:|55%|,|JavaScript|:|21%|,or null
		 *sourceforge:JavaScript, Groovy, Java or null
		 *oschina:<PHP>,<JavaScript> or null
		 *apache:一般只有一个 
		 *freecode:<jdbc>,<Java>,<Database development>
		 */
		//如果oschina没有language，则返回false
		if (str1==null||str1.equals("")||str2==null||str2.equals(""))
			return false;
		String []arr = str1.split(",");
		Pattern p = Pattern.compile("<(.*?)>");
		for(int i=0;i<arr.length;i++){
			Matcher m = p.matcher(arr[i]);
			 if(m.find()) {
				 String tmp = m.group(1)+",";
				 String tmp2 = m.group(1)+"|";
				 String tmp3 = "<"+m.group(1)+">";
				 if(str2.toLowerCase().indexOf(tmp.toLowerCase())!=-1)//对应于sourceforge
					 return true;
				 if(str2.toLowerCase().indexOf(tmp2.toLowerCase())!=-1)//对应于openhub
					 return true;
				 if(str2.toLowerCase().indexOf(tmp3.toLowerCase())!=-1)//对应于freecode
					 return true;
				 if(str2.toLowerCase().equals(m.group(1).toLowerCase()))//对应于apahce
					 return true;
		}
		}
		return false;
	}
	
	/**
	 * 存在（）的将括号中的信息提取出来 去除常用词后得到另外一个linkName
	 * @param str
	 * @return
	 */
	public static List<String> removeBracket(String str){
		List<String> result = new ArrayList<String>();
		int index1 = -1;
		int index2 = -1;
		int index_last1 = -1;
		int index_last2 = -1;
		String strInBracket = null;
		String strInBracket2 = null;
		
		index1 = str.indexOf("(");
		index2 = str.indexOf(")");
		index_last1 = str.lastIndexOf("(");
		if(index1 > 0){
			result.add(str.substring(0,index1).trim());
			if(index2 > index1){
				strInBracket = str.substring(index1 + 1, index2);
			}
			if(index1 != index_last1){
				index_last2 = str.lastIndexOf(")");
				strInBracket2 = str.substring(index_last1 + 1, index_last2);
			}
		}else{
			index1 = str.indexOf("（");
			index2 = str.indexOf("）");
			index_last1 = str.lastIndexOf("（");
			if(index1 > 0){
				result.add(str.substring(0,index1).trim());
				if(index2 > index1){
					strInBracket = str.substring(index1 + 1, index2);
				}
				if(index1 != index_last1){
					index_last2 = str.lastIndexOf(")");
					strInBracket2 = str.substring(index_last1 + 1, index_last2);
				}
			}else{
				index1 = str.indexOf("[");
				index2 = str.indexOf("]");
				if(index1 > 0){
					result.add(str.substring(0,index1).trim());
					if(index2 > index1){
						strInBracket = str.substring(index1 + 1, index2);
					}
				}else{
					index1 = str.indexOf("【");
					index2 = str.indexOf("】");
					if(index1 > 0){
						result.add(str.substring(0,index1).trim());
						if(index2 > index1){
							strInBracket = str.substring(index1 + 1, index2);
						}
					}else{
						index1 = str.indexOf("{");
						index2 = str.indexOf("}");
						if(index1 > 0){
							result.add(str.substring(0,index1).trim());
							if(index2 > index1){
								strInBracket = str.substring(index1 + 1, index2);
							}
						}else{
							result.add(str);
						}
					}
				}
			}
		}
		if(strInBracket != null){
			result.add(strInBracket.trim());//暂时没有对括号中的数据进行常用词排除处理
		}
		if(strInBracket2 != null){
			result.add(strInBracket2.trim());//暂时没有对括号中的数据进行常用词排除处理
		}
		
		return result;
	}
	
	
	/**
	 * 包含逗号都去掉
	 * @param str
	 * @return
	 */
	public static String removeComma(String str){
		int index1 = str.indexOf(",");
		if(index1 > 0){
			return null;
		}
		int index2 = str.indexOf("，");
		if(index2 > 0){
			return null;
		}
		return str;
	}
	
	public static String removeFirstEndComma(String str){
		int index1 = str.indexOf(",");
		if(index1==0){
			try{
			str = str.substring(1);
			}catch(Exception e){
				return null;
			}
		}
		int index2 = str.lastIndexOf(",");
		if(index2 == str.length()-1){
			
			try{
				str = str.substring(0,index2);
				}catch(Exception e){
					return null;
				}
		}
		return str;
	}
	
	public static String removeFirstComma(String str){
		int index1 = str.indexOf(",");
		if(index1==0){
			try{
				str = str.substring(1);
				}catch(Exception e){
					return null;
				}
		}
		
		return str;
	}
	
	public static String removeDupIdInStr(String sourceStr){
		String [] arr = null;
		sourceStr = StringHandler.removeFirstEndComma(sourceStr);
		StringBuilder desStr = new StringBuilder(",");
		if(sourceStr!=null && !sourceStr.equals(""))
			arr = sourceStr.split(",");
		Set<Integer> tmpIdSet = new HashSet<Integer>();
		for(String str:arr){
			tmpIdSet.add(Integer.parseInt(str));
		}
		for(int id:tmpIdSet){
			desStr.append(String.valueOf(id));
			desStr.append(",");
		}
		return desStr.toString();
	}
	
	/**
	 * 字符串中有指示代词 去掉指示代词 the
	 * @param str
	 * @return
	 */
	public static String removeDWords(String str, List<String> dWords){
		String result = str;
		int lastIndex = -1;
		for(int i = 0; i < dWords.size(); i++){
			String dWord = dWords.get(i);
			int indexTmp = -1;
			if((indexTmp = str.lastIndexOf(dWord)) > lastIndex){
				lastIndex = indexTmp + dWord.length();
			}
		}
		if(lastIndex > 0){
			result = str.substring(lastIndex).trim();
		}
		return result;
	}
	
	
	public static List<String> extractOtherDescriptions(String des){
		List<String> result = new ArrayList<String>();
		//提取括号中的主副描述信息
		List<String> resultStep1 = removeBracket(des);
		for(String str:resultStep1){
			if(str == null)
				return null;
			result.add(str);
			List<String> knownAss = FileReader.read("./files/known_as.txt");
			for(String tmp:knownAss){
				int index = str.toLowerCase().indexOf(tmp);
				if(index > 0){
					result.remove(0);
					String tmp2 = str.substring(index + tmp.length()).trim();
					String[] resultTmp = tmp2.split(" and ");
					for(String s:resultTmp){
						String[] resultTmp2 = s.split(" or ");
						for(String s2:resultTmp2){
							result.add(s2);
						}
					}
					break;
				}
			}
		}
		return result;
		
	}
	
	public static boolean getFullName(String shortName, String synonym,int a){
		//查看当前的同义词是不是含不含有全称
		String[] words = synonym.toLowerCase().split(" ");
		String shortenWord = "";
		for(int i = 0; i < words.length; i++){
			String word = words[i];
			String tmp = "";
			if(word.length() == 1)
				tmp = word;
			else
				if(word.length() > 0)
				 tmp = word.substring(0, 1);//取出第一个英文字符
			
				shortenWord += tmp;
		}
		
		if(shortenWord.toLowerCase().equals(shortName.toLowerCase()))
			return true;
		
		return false;
	}
	
	//查看若干个char有没有在list中连续单词的首字母出现 如果出现返回连续出现的单词组成的字符串
	public static String getFullName(String shortName, String synonym){
		String fullName = "";
		
		//查看当前的同义词是不是含不含有全称
		String[] words = synonym.toLowerCase().split(" ");
		String shortenWord = "";
		Map<Integer,String> wordMap = new HashMap<Integer,String>();//记录每个词对应的下标和词的全称
		for(int i = 0; i < words.length; i++){
			String word = words[i];

				String tmp = word.substring(0, 1);//取出第一个英文字符
				shortenWord += tmp;
				wordMap.put(i, word);
		}
//			//判断shortName(有时候不只是简称 ：501759jiipco! (Java Internal Interprocess Communication))是否包含shortenWord
//			if(shortName.contains(shortenWord)){
//				fullName = synonym;
//				return fullName;
//				
//			}
		//判断shortName是不是shortenWord中的一部分
		int index_start = shortenWord.indexOf(shortName);
		int index_end = index_start + shortName.length()-1;
		if(index_start >= 0){
			//找到map中对应下表的词全称
			for(int j = index_start; j <= index_end; j++){
				if(!wordMap.containsKey(j)){
					fullName = "";
					break;//表示中间有单词不仅仅包含英文字母 因此没有存到相应的map中
				}
				String w = wordMap.get(j);
				fullName += w + " ";
			}
			if(!"".equals(fullName)){
				
				return fullName.substring(0, fullName.length()-1);
			}
		}
		
		return fullName;
	}
	
	public static boolean isFullOrShort(String str1,String str2)
	{
		if(getFullName(str1,str2,1) || getFullName(str2, str1,1))
			return true;
		
		return false;
	}
	
	public static boolean specialIsFullOrShort(String shortName, String fullName)
	{
		//首先获取两个字符串中单词的
		String[] words_fullName= fullName.toLowerCase().split(" ");
		String[] words_shortName = shortName.toLowerCase().split(" ");
		
		if(words_fullName.length==1 && words_shortName.length==1)
		{
			return false;
		}
		
		if(words_shortName.length == 1 && words_fullName.length > 1 )
		{
			if(specialIsFullOrShorDetail(shortName,fullName))
				return true;
		}
		else
		{
			if(specialIsFullOrShorDetail(fullName,shortName))
				return true;
		}

		return false;
	}
	public static boolean specialIsFullOrShorDetail(String shortName, String fullName)
	{
		//首先获取两个字符串中单词的个数
		String[] words_fullName = fullName.toLowerCase().split(" ");
		//String[] words_shortName = shortName.toLowerCase().split(" ");
		
		int positionFlag = -1;
		int matchCount=0;
		int tmpFlag;
		
		//要求全写中各个单词的首字母必须在缩写中出现而且是顺序出现或最多有一个不出现在缩写中。
		for(int i = 0; i < words_fullName.length; i++){
			String word = words_fullName[i].toLowerCase();
			String tmp = "";//取出第一个英文字符
			if(word.length() == 1)
				tmp = word;
			else
				if(word.length() > 0)
				 tmp = word.substring(0, 1);//取出第一个英文字符
			if(shortName.toLowerCase().contains(tmp))
			{
				
//				tmpFlag = shortName.indexOf(tmp);
//				if(tmpFlag > positionFlag)
//				{
					matchCount++;
//					positionFlag = tmpFlag;
//				}
			}		    	
		}
		
		/**
		如果满足全写中各个单词的首字母都在缩写中顺序出现就接着
	            判断缩写中所有字幕是否都在全写中出现
		 */
		if(matchCount > words_fullName.length-2)
		{
			if(isAllContained(shortName,fullName))
				return true;
		}
		else 
			return false;
		
		return false;
	}
	
	//查看若干个char有没有在list中连续单词的首字母出现 如果出现返回连续出现的单词组成的字符串
	public static String getFullName(String shortName, List<String> list){
		String fullName = "";
		for(String synonym:list){
			//查看当前的同义词是不是含不含有全称
			String[] words = synonym.split(" ");
			String shortenWord = "";
			Map<Integer,String> wordMap = new HashMap<Integer,String>();//记录每个词对应的下标和词的全称
			for(int i = 0; i < words.length; i++){
				String word = words[i];
//					if(RegexHandler.othersExceptEng(word)){
//						continue;//表示当前的词不止含有英文 不满足条件
//					}else{
					String tmp = word.substring(0, 1);//取出第一个英文字符
					shortenWord += tmp;
					wordMap.put(i, word);
//					}
			}
			//判断shortName是不是shortenWord中的一部分
			shortenWord = shortenWord.toLowerCase();
			int index_start = shortenWord.indexOf(shortName);
			int index_end = index_start + shortName.length()-1;
			if(index_start >= 0){
				//找到map中对应下表的词全称
				for(int j = index_start; j <= index_end; j++){
					if(!wordMap.containsKey(j)){
						fullName = "";
						break;//表示中间有单词不仅仅包含英文字母 因此没有存到相应的map中
					}
					String w = wordMap.get(j);
					fullName += w + " ";
				}
				if(!"".equals(fullName)){
					
					return fullName.substring(0, fullName.length()-1);
				}
			}
			
		}
		return fullName;
	}
	
	//判断是否shortName中所有字符都在fullName中出现，是，则返回真；否，则返回false
		private static boolean isAllContained(String shortName, String fullName) {
			// TODO Auto-generated method stub
			int matchCount =0;
//			for(int i=0;i<shortName.length();i++)
//				if(fullName.toLowerCase().contains(shortName.substring(i, i+1)))
//					matchCount++;
//			
//			if(matchCount > shortName.length()-2)
//				return true;
			int matchPosition;
			for(int j=0;j<shortName.length();j++)
			{
				matchPosition = fullName.toLowerCase().indexOf(shortName.substring(j,j+1).toLowerCase());
				if(matchPosition > -1)
				{
					fullName = fullName.substring(matchPosition);
					matchCount ++;
				}
			}
			
			if(matchCount > shortName.length()-2)
				return true;
					
			return false;	
		}
	
	//查看字符串中 在后面的list里面有没有首字母缩写的结果
		public static String getShortName(String fullName, List<String> list){
			//判断fullName是不是全英文的形式 如果不是 返回""
//			boolean onlyEng = RegexHandler.othersExceptEng(fullName.toLowerCase());
//			if(onlyEng)
//				return "";
			//如果fullName没有空格 表示是一个单词 默认没有缩写形式
			String[] words = fullName.split(" ");
			if(words.length <= 1)
				return "";
			//获取空格分词后每个英文单词的首字母
			String shortName = "";
			for(String word:words){
				String firstLetter = word.substring(0, 1).toLowerCase();
				shortName += firstLetter;
			}
			for(String str:list){
				if(str.toLowerCase().equals(shortName)|| str.toLowerCase().indexOf(shortName)!=-1)
					return str;//表示描述信息中出现了缩写形式
			}
			return "";
		}

	//查看字符串中 在后面的list里面有没有首字母缩写的结果
	public static String getShortName(String fullName, String str){
		//判断fullName是不是全英文的形式 如果不是 返回""
//		boolean onlyEng = RegexHandler.othersExceptEng(fullName.toLowerCase());
//		if(onlyEng)
//			return "";
		//如果fullName没有空格 表示是一个单词 默认没有缩写形式
		fullName = fullName.trim();
		String[] words = fullName.split(" ");
		if(words.length <= 1)
			return "";
		//获取空格分词后每个英文单词的首字母
		String shortName = "";
		for(String word:words){
			String firstLetter = word.substring(0, 1).toLowerCase();
			shortName += firstLetter;
		}
		
		if(str.equals(shortName) || str.indexOf(shortName)!=-1)
			return shortName;//表示描述信息中出现了缩写形式
		return "";
	}
	
	public static boolean specialIsFullOrShortForGitPrj(String shortName, String fullName)
	{
		String[] splitFullName = null;
		int containedNum = 0;//记录shortName中包含在fullName中的单词的个数

		if(fullName.indexOf("_") > -1)
		   splitFullName = fullName.split("-");
		if(fullName.indexOf("-") > -1)
			splitFullName = fullName.split("_");
		else 
			splitFullName = fullName.split(" ");
		
		if(splitFullName != null)
			for(String tmp:splitFullName)
				if(shortName.contains(tmp))
					containedNum++;
		if(containedNum > 2)
			return false;
		
		if(fullName.contains(shortName) || shortName.contains(fullName))
			return false;
		//首先获取两个字符串中单词的
		String[] words_fullName= fullName.toLowerCase().split(" ");
		String[] words_shortName = shortName.toLowerCase().split(" ");
		
		if(words_fullName.length==1 && words_shortName.length==1)
			return false;
		
		if(words_shortName.length == 1 && words_fullName.length > 1 )
		{
			if(specialIsFullOrShorDetail(shortName,fullName))
			{
				return true;
			}
		}
		else
		{
			if(specialIsFullOrShorDetail(fullName,shortName))
			{
				return true;
			}
		}

		return false;
	}
}
